package com.libui.thirdpartsdk.wechat

import com.libbase.Weak
import com.libui.thirdpartsdk.SDKInterface
import com.libui.thirdpartsdk.login.Login
import com.libui.thirdpartsdk.login.LoginCompletion
import com.libui.thirdpartsdk.login.models.LoginModel
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.addTo
import java.util.*


class WechatLogin(sdk: WechatSDK) : Login {
    companion object {
        val builder = object : Login.Builder {

            override val type: String = "wechat"

            override val name: String = "微信登录"

            override val icon: String? = null

            override fun build(sdk: SDKInterface): Login {
                return WechatLogin(sdk as WechatSDK)
            }
        }
    }

    override val type: String
        get() = builder.type

    override val name: String
        get() = builder.name

    override val icon: String?
        get() = builder.icon

    private var wxApi: IWXAPI? by Weak { sdk.wxApi }

    private var compositeDisposable = CompositeDisposable()

    private var completion: LoginCompletion? = null

    private var requestId: String? = null

    init {
        sdk.authRespObservable
            .subscribe { resp ->
                if (resp.state != requestId) {
                    return@subscribe
                }

                if (resp.errCode == BaseResp.ErrCode.ERR_OK) {
                    completion?.let {
                        it(
                            true, null,
                            LoginModel(resp.code, null, null, null)
                        )
                    }
                } else {
                    completion?.let { it(false, null, null) }
                }

                completion = null
                compositeDisposable.dispose()
            }
            .addTo(compositeDisposable)
    }

    override fun login(completion: LoginCompletion?) {
        this.completion = completion
        val requestId = UUID.randomUUID().toString()
        this.requestId = requestId

        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"
        req.state = requestId
        wxApi?.sendReq(req)
    }
}